package algorithm;

public class leetcode_0057 {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        int a=newInterval[0];
        int b=newInterval[1];
        int len=intervals.length;
        if(len==0) {
            int[][] result=new int[1][2];
            result[0]=newInterval;
            return result;
        }
        int left=len;
        boolean flag=false;
            for(int i=0;i<len;++i){
                if(intervals[i][0]<=a&&intervals[i][1]>=a){
                    flag=true;
                    left=i;
                }
                if(intervals[i][0]>a){
                    flag=false;
                    left=i;
                }
            }
        int right=len;
        boolean flag2=false;
        for(int i=0;i<len;++i){
            if(intervals[i][0]<=b&&intervals[i][1]>=b){
                flag2=true;
                left=i;
            }
            if(intervals[i][0]>b){
                flag2=false;
                left=i-1;
            }
        }
        int len2=len-(right-left);
        if(flag==false&&left>right) len2++;
        int [][] result=new int[len2][2];
        for(int i=0;i<left;++i){
            result[i]=intervals[i];
        }
        for(int i=left+1;i<len2;++i){
            result[i]=intervals[right+i-left];
        }
        if(flag) result[left][0]=intervals[left][0];
        else result[left][0]=a;
        if(flag2) result[left][1]=intervals[right][1];
        else  result[left][1]=b;
        return result;
    }
}
